package com.gitee.huanminabc.utils_tools.security.dal.redis.impl;

import com.alibaba.fastjson.JSON;
import com.gitee.huanminabc.utils_tools.redis.redisTemplate.utils.RedisTemplateUtil;
import com.gitee.huanminabc.utils_tools.security.dal.redis.RedisSecurityService;
import com.gitee.huanminabc.utils_tools.security.enums.AuthEnum;
import com.gitee.huanminabc.utils_tools.security.vo.LoginUserVo;
import org.redisson.client.RedisException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author huanmin
 */
@Service
public class RedisSecurityServiceImpl implements RedisSecurityService {
    private final String PREFIX = "login:";
    private final String PREFIX_MOCK_TOKEN = "mockToken";
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Override
    public LoginUserVo getLoginUserDto(String account)throws RedisException {
        String redisKey =PREFIX + account;
        Object json = redisTemplateUtil.get(redisKey);
        // redis中用户不存在
        if (Objects.isNull(json)) {
            throw new RedisException(AuthEnum.REDIS_USER_NOT_EXIST.getShow());
        }
        String jsonUser = json.toString();
        return JSON.parseObject(jsonUser, LoginUserVo.class);
    }

    @Override
    public long getAccountExpire(String account) {
        String redisKey = PREFIX + account;
        return redisTemplateUtil.getExpire(redisKey);
    }

    @Override
    public void setLoginUserDto(LoginUserVo loginUserDto, long time) {
        String redisKey = PREFIX + loginUserDto.getUsername();
        String jsonString = JSON.toJSONString(loginUserDto);
        redisTemplateUtil.set(redisKey, jsonString, time);
    }

    @Override
    public void deleteLoginUserDto(String account) {
        String redisKey = PREFIX + account;
        redisTemplateUtil.del(redisKey);
    }

    @Override
    public void setMockToken(String hash,String jwt, long time) {

        redisTemplateUtil.hset(PREFIX_MOCK_TOKEN,hash,jwt,time) ; // 用于反复获取token,不用每次都去数据库查
    }


    @Override
    public String getMockToken(String hash) {
        return (String)redisTemplateUtil.hget(PREFIX_MOCK_TOKEN, hash);
    }
}
